package com.power.sifa.util.service.impl;

import java.io.IOException;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

/**
 * 讯飞星火AI socket的监听器
 * 监听该问题的陆续回答内容
 * @author 81814
 *
 */
@Slf4j
public class ChatListener extends WebSocketListener{
	/**
	 * 讯飞注册应用ID
	 */
    private String appid;

    /**
     * 发出的问题
     */
    private String question;

    /**
     * 陆续返回的回答，组合成一段话
     */
    private StringBuffer answer;

    /**
     * 是否活动监听
     * true 监听中，可能是初始化或发出了问题
     * false 监听结束，回答已全部搜集组合成answer
     */
    private Boolean running;

	public ChatListener(String appid, String question) {
		this.appid=appid;
		this.question=question;
		this.running=true;
	}

	public Boolean isRunning() {
		return running;
	}

	public String getAnswer() {
		String re=null;
		if(answer!=null) {
			re=answer.toString();
		}
		return re;
	}

	@Override
	public void onFailure(WebSocket webSocket, Throwable t, Response response) {
		super.onFailure(webSocket, t, response);
		running=false;
		try {
            if (null != response) {
                log.error("WebSocket failure code: {} body:{}", response.code(), response.body().string());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
	}

	@Override
	public void onMessage(WebSocket webSocket, String text) {
		JSONObject result=JSON.parseObject(text);
		JSONObject header=result.getJSONObject("header");
		Integer code=header.getInteger("code");
		if(code!=0) {
            log.error("WebSocket message error code: {}", code);
			webSocket.close(1000, "");
			return;
		}

		JSONObject payload=result.getJSONObject("payload");
		JSONObject choices=payload.getJSONObject("choices");
		Integer status=choices.getInteger("status");
		if(status==0) {
			// 回答的第一句
			answer=new StringBuffer();
		}

		JSONArray txt=choices.getJSONArray("text");

		for(int i=0;i<txt.size(); i++) {
			JSONObject row=txt.getJSONObject(i);
			answer.append(row.getString("content"));
		}

		if(status==2) {
			// 回答的最后一句
            log.info("WebSocket answer: {}", answer);
			running=false;
			webSocket.close(0, "Bye!");
		}
	}

	@Override
	public void onOpen(WebSocket webSocket, Response response) {
		super.onOpen(webSocket, response);
		JSONObject requestJson = new JSONObject();

		JSONObject header = new JSONObject(); // header参数
		header.put("app_id", appid);
		header.put("uid", UUID.randomUUID().toString().substring(0, 10));

		JSONObject parameter = new JSONObject(); // parameter参数
		JSONObject chat = new JSONObject();
		chat.put("domain", "generalv2");
		chat.put("temperature", 0.5);
		chat.put("max_tokens", 4096);
		parameter.put("chat", chat);

		JSONObject payload = new JSONObject(); // payload参数
		JSONObject message = new JSONObject();
		JSONArray text = new JSONArray();

		JSONObject roleContent = new JSONObject();
		roleContent.put("role", "user");
		roleContent.put("content", question);
		text.add(roleContent);

		message.put("text", text);
		payload.put("message", message);

		requestJson.put("header", header);
		requestJson.put("parameter", parameter);
		requestJson.put("payload", payload);
//        log.info("WebSocket requestJson: {}", requestJson); // 可以打印看每次的传参明细
		webSocket.send(requestJson.toString());
	}

}
